package com.bihua.iot.dynamicScript.pool;

import javax.script.CompiledScript;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.DestroyMode;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.script.ScriptUtil;
import jdk.nashorn.api.scripting.NashornScriptEngine;

public class ScriptPooledObjectFactory  extends BasePooledObjectFactory<CompiledScript> {
	private static final Logger logger = LoggerFactory.getLogger(ScriptPooledObjectFactory.class);

	private final String nameOrExtOrMime;
	private final String script;

	public ScriptPooledObjectFactory(String nameOrExtOrMime, String script) {
		this.nameOrExtOrMime = nameOrExtOrMime;
		this.script = script;
	}

	@Override
	public CompiledScript create() throws Exception {
		final NashornScriptEngine engine = (NashornScriptEngine) ScriptUtil.createScript(nameOrExtOrMime);
		//compiledScript是单例
		final CompiledScript compiledScript  = engine.compile(script);
		logger.info("begin create script engine,nameOrExtOrMime: {}， script:{}", nameOrExtOrMime, script);
		return compiledScript;
	}

	@Override
	public PooledObject<CompiledScript> wrap(CompiledScript obj) {
		return new DefaultPooledObject<>(obj);
	}

	@Override
	public void destroyObject(PooledObject<CompiledScript> p, DestroyMode destroyMode) throws Exception {
		super.destroyObject(p);
	}
}
